#include "threadmanager.h"

#include <QTimer>

ThreadManager::ThreadManager(QObject *parent)
    : QObject(parent)
    , queue_(nullptr)
    , loaderThread_(nullptr)
    , processThread_(nullptr)
    , counterThread_(nullptr)
{
    // 创建安全队列
    queue_ = new SafeQueue(15, this);
    // 创建两个子线程，传入安全队列
    loaderThread_ = new LoaderThread(queue_, this);
    processThread_ = new ProcessThread(queue_, this);
    counterThread_ = new CounterThread(this);
    // 初始化信号槽
    initSlots();
}

ThreadManager::~ThreadManager()
{
    stopProcessing();
    // 安全停止加载线程
    if (loaderThread_)
    {
        loaderThread_->wait(3000);
        if (loaderThread_->isRunning())
        {
            loaderThread_->terminate();
            loaderThread_->wait(1000);
        }
    }
    // 安全停止处理线程
    if (processThread_)
    {
        processThread_->wait(3000);
        if (processThread_->isRunning())
        {
            processThread_->terminate();
            processThread_->wait(1000);
        }
    }
    // 安全停止计数线程
    if (counterThread_)
    {
        counterThread_->wait(3000);
        if (counterThread_->isRunning())
        {
            counterThread_->terminate();
            counterThread_->wait(1000);
        }
    }
}

void ThreadManager::initSlots()
{
    // 连接信号槽
    connect(queue_, &SafeQueue::queueFull, this, &ThreadManager::onQueueFull);
    connect(loaderThread_, &LoaderThread::errorOccurred, this, &ThreadManager::onError);
    connect(processThread_, &ProcessThread::errorOccurred, this, &ThreadManager::onError);
    connect(loaderThread_, &LoaderThread::totalCountUpdated, this, &ThreadManager::onTotalCount);
    connect(counterThread_, &CounterThread::countUpdated, this, &ThreadManager::onCountUpdated);
    connect(counterThread_, &CounterThread::limitExceeded, this, &ThreadManager::onLimitExceeded);
    connect(processThread_, &ProcessThread::processedAndRegions, this, &ThreadManager::onProcessedAndRegions);
    connect(this, &ThreadManager::regionReceived, counterThread_, &CounterThread::onRegionsReceived);
}

void ThreadManager::setPathAndStartThread(const QString& path)
{
    // 停止当前线程并重置队列
    stopProcessing();
    queue_->reset();
    // 设置加载线程的图片路径
    loaderThread_->setImagePath(path);
    // 重置处理线程计数
    processThread_->resetProcessCount();
    // 重置计数线程
    counterThread_->resetCounts();
    // 启动三个线程
    loaderThread_->start();
    processThread_->start();
    counterThread_->start();
}

void ThreadManager::stopProcessing()
{
    if (loaderThread_)
    {
        loaderThread_->stopProcessing();
    }
    if (processThread_)
    {
        processThread_->stopProcessing();
    }
    if (counterThread_)
    {
        counterThread_->stopProcessing();
    }
    if (queue_)
    {
        queue_->wakeAll();
    }
}

void ThreadManager::pauseProcessing()
{
    if (loaderThread_)
    {
        loaderThread_->pauseProcessing();
    }
    if (processThread_)
    {
        processThread_->pauseProcessing();
    }
}

void ThreadManager::keepProcessing()
{
    if (loaderThread_)
    {
        loaderThread_->keepProcessing();
    }
    if (processThread_)
    {
        processThread_->keepProcessing();
    }
}

void ThreadManager::setCurrManualIndex(const int index)
{
    loaderThread_->setIndex(index);
    loaderThread_->setManual(true);
    loaderThread_->keepProcessing();

    processThread_->setIndex(index);
    processThread_->setManual(true);
    processThread_->keepProcessing();
}

void ThreadManager::setCountMode(int mode)
{
    counterThread_->setCountMode(mode);
}

void ThreadManager::setLimits(int totalLimit, int leftLimit, int rightLimit)
{
    counterThread_->setLimits(totalLimit, leftLimit, rightLimit);
}

void ThreadManager::setManualMode(bool isManual)
{
    isManualMode_.store(isManual);
}

bool ThreadManager::isManualMode() const
{
    return isManualMode_.load();
}

void ThreadManager::onQueueFull()
{
    // 发送给主线程
    emit queueFull();
}

void ThreadManager::onError(const QString &errorMessage)
{
    emit processError(errorMessage);
}

void ThreadManager::onTotalCount(const int count)
{
    emit totalCountUpdated(count);
}

void ThreadManager::onLimitExceeded()
{
    // 通知主线程超过上限
    emit LimitExceeded();
    // 自动遍历图片的模式下执行暂停和倒计时逻辑
    if (!isManualMode())
    {
        // 发送开始倒计时信号
        emit startCountdown(2);
        // 超过设置上限时，暂停所有线程
        pauseProcessing();
        QTimer::singleShot(2000, this, [this](){
            // 恢复线程运行，这里也需要确认非手动模式，避免状态切换冲突
            if(!isManualMode())
            {
                keepProcessing();
            }
        });
    }
}

void ThreadManager::onCountUpdated(const CountResult &result)
{
    emit countUpdated(result);
}

void ThreadManager::onProcessedAndRegions(const ProcessResult &result, const vector<XVL::XVRegion> &regions, int width)
{
    // 先显示结果
    emit imageProcessed(result);
    // 再处理计数
    emit regionReceived(width, regions);
}
